use std::sync::Arc;
use actix_web::web::{Json, Path};
use actix_web::{get, post, web::Data, Responder};
use sqlx::MySqlPool;
use crate::business::entity::role::Role;
use crate::business::service::role_service::RoleService;
use crate::extends::core::context::app_context_beans::AppContextBeans;
use crate::extends::core::errors::response_code_enums::ResponseCodeEnum;
use crate::extends::core::http::request_headers::RequestHeaders;
use crate::extends::core::pager::page_helper::PageHelper;
use crate::extends::core::response::reponse_data::*;

/// 处理角色分页查询请求
///
/// # 参数
/// * `headers` - 请求头部信息
/// * `vo` - 包含分页信息的JSON对象
/// * `ctx_beans` - 应用上下文容器
///
/// # 返回值
/// 返回包含角色列表的JSON响应
#[post("/admin/role/list")]
pub async fn list(
    headers: RequestHeaders,
    Json(search): Json<PageHelper<Role>>,
    ctx_beans: Data<AppContextBeans>,
) -> impl Responder {
    log::info!("{:?} ", search);
    // 使用提取的头部参数
    headers.print();

    // 获取 role_service 并在失败时引发错误
    let role_service: Arc<RoleService> = match ctx_beans.get_bean("role_service") {
        Ok(service) => service,
        Err(err) => {
            log::error!("Failed to retrieve role_service: {}", err);
            return R::error(ResponseCodeEnum::INTERNAL_SERVER_ERROR); // 返回合适的错误响应
        }
    };

    let result = role_service.find(&search).await;
    return R::success(Some(result));
}

/// 处理保存新角色的请求
///
/// # 参数
/// * `vo` - 包含角色详细信息的JSON对象
/// * `pool` - MySQL数据库连接池
///
/// # 返回值
/// 返回指示操作成功或失败的JSON响应
#[post("/admin/role/save")]
pub async fn save(Json(vo): Json<Role>, pool: Data<MySqlPool>) -> impl Responder {
    log::info!("{:?} ", vo);
    let result = Role::save(&vo, &pool).await;
    return R::success(result);
}

/// 处理根据ID删除角色的请求
///
/// # 参数
/// * `id` - 要删除的角色ID
/// * `pool` - MySQL数据库连接池
///
/// # 返回值
/// 返回指示操作成功或失败的JSON响应
#[get("/admin/role/delete/{id}")]
pub async fn delete(id: Path<i32>, pool: Data<MySqlPool>) -> impl Responder {
    log::info!("{:?} ", id);
    let result = Role::delete(&id, &pool).await;
    return R::success(result);
}

/// 处理更新角色详细信息的请求
///
/// # 参数
/// * `vo` - 包含更新后角色详细信息的JSON对象
/// * `pool` - MySQL数据库连接池
///
/// # 返回值
/// 返回指示操作成功或失败的JSON响应
#[post("/admin/role/update")]
pub async fn update(Json(vo): Json<Role>, pool: Data<MySqlPool>) -> impl Responder {
    log::info!("{:?} ", vo);
    let result = Role::update(&vo, &pool).await;
    return R::success(result);
}

/// 处理根据ID获取角色详细信息的请求
///
/// # 参数
/// * `id` - 要检索的角色ID
/// * `pool` - MySQL数据库连接池
///
/// # 返回值
/// 返回包含角色详细信息的JSON响应
#[get("/admin/role/detail/{id}")]
pub async fn detail(id: Path<i32>, pool: Data<MySqlPool>) -> impl Responder {
    log::info!("{:?} ", id);
    let result = Role::find_by_id(&id, &pool).await;
    return R::success(result);
}
